import json
import os

from api import read2
from flask import Flask, request
from flask_cors import cross_origin
from kv import DBClass

db = DBClass()

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = '/root/note-flask/static/upload'


@app.route('/')
@cross_origin()
def index():
    return 'index'


@app.route('/set', methods=['POST'])
@cross_origin(methods=['POST'])
def set_():
    data = request.json
    key = data['key']
    value = data['value']
    type_ = data['type']

    value = {'value': value, 'type': type_}
    db.set(key, value)
    return ''


@app.route('/get')
@cross_origin()
def get_():
    key = request.args.get('key')
    try:
        value = db.get(key)
    except KeyError as e:
        value = {'value': '', 'type': 'none'}

    return json.dumps(value)


@app.route('/upload', methods=['post'])
@cross_origin()
def upload():
    file = request.files['file']
    filename = file.filename
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

    if filename.endswith(('.png', '.jpg', '.svg')):
        type_ = 'img'
    elif filename.endswith(('.mp3', '.flac')):
        type_ = 'audio'
    else:
        type_ = 'file'
    db.set(filename.split('.')[0], {'type': type_, 'value': filename})

    return json.dumps({
        'success': True
    })


@app.route('/keys')
@cross_origin()
def keys():
    return json.dumps(db.keys())


@app.route('/reload')
@cross_origin()
def reload():
    global db
    db = DBClass()
    return ''


@app.route('/api', methods=['post'])
@cross_origin(methods=['post'])
def hello_world2():
    q = request.json['q']
    node = read2(q)
    return json.dumps(node.render_to_json())


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8001, debug=True)
